<template>
  <el-card>
    <el-cascader
      v-model="categoryId"
      :options="options"
      :props="props"
      :disabled="disabled"
      @change="handleChange"
      size="medium"
      placeholder="请选择分类"
      :style="{ width: width }"
    >
      <template slot-scope="{ node, data }">
        <span>{{ data.name }}</span>
      </template>
    </el-cascader>
  </el-card>
</template>

<script>
export default {
  name: 'CategorySelect',
  props: ['width', 'disabled'],
  data() {
    return {
      categoryId: [],
      options: [],
      props: {
        value: 'id',
        label: 'name',
        lazy: true,
        // 加载二三级分类
        lazyLoad: async (node, resolve) => {
          if (!node.data || !node.data.id) {
            resolve([])
            return
          }
          const { id, type, name } = node.data
          if (type == 'c1') {
            const res = await this.$API.attr.getCategory2List(id)
            if (res.code == 200) {
              // 添加2级分类标识
              res.data.forEach((value) => {
                value.type = 'c2'
              })
              resolve(res.data)
            }
          }
          if (type == 'c2') {
            const res = await this.$API.attr.getCategory3List(id)
            if (res.code == 200) {
              // 添加3级分类标识
              res.data.forEach((value) => {
                value.type = 'c3'
                // 最后一级
                value.leaf = true
              })
              resolve(res.data)
            }
          }
          if (type == 'c3') {
            resolve()
          }
        }
      }
    }
  },

  methods: {
    // 获取一级分类
    async getC1List() {
      let res = await this.$API.attr.getCategory1List()
      if (res.code == 200) {
        // 添加一级分类标识
        res.data.forEach((value) => {
          value.type = 'c1'
        })
        this.options = res.data
      }
    },
    // 获取3个分类的ID
    handleChange(data) {
      this.$emit('getCategoryId', { c1: data[0], c2: data[1], c3: data[2] })
    }
  },
  created() {
    this.getC1List()
  }
}
</script>

<style></style>
